/**
 * Created by Toma on 2016/11/21.
 * 折线图
 */

var H5ComponentPolyline = function (name, cfg) {
  var compontent = new H5ComonentBase(name, cfg);

  // 绘制网格线
  var WIDTH = cfg.width;
  var HEIGHT = cfg.height;

  // 添加画布
  var cns = document.createElement('canvas');
  var ctx = cns.getContext('2d');
  cns.width = ctx.width = WIDTH;
  cns.height = ctx.height = HEIGHT;
  compontent.append(cns);

  var step = 10;
  ctx.beginPath();
  ctx.lineWidth = 1;
  ctx.strokeStyle = '#AAA';

  window.ctx = ctx;
  for (var i = 0; i < step + 1; i++) {
    var y = (HEIGHT / step) * i;
    ctx.moveTo(0, y);
    ctx.lineTo(WIDTH, y);
  }
  // 垂直线
  step = cfg.data.length + 1;
  var text_w = WIDTH / step;
  for (var i = 0; i < step + 1; i++) {
    var x = (WIDTH / step) * i;
    ctx.moveTo(x, 0);
    ctx.lineTo(x, HEIGHT);

    if (cfg.data[i]) {
      var text = $('<div class="text">');
      text.text(cfg.data[i][0]);
      text.css({'width': text_w, 'left': x / 2});
      compontent.append(text);
    }
  }
  ctx.stroke();

  /**
   * 绘制折线
   * @param per 传入百分比
   */
  var cns = document.createElement('canvas');
  var ctx = cns.getContext('2d');
  cns.width = ctx.width = WIDTH;
  cns.height = ctx.height = HEIGHT;
  compontent.append(cns);

  var draw = function (per) {
    ctx.clearRect(0,0,WIDTH,HEIGHT);
    // 画点
    ctx.beginPath();
    ctx.lineWidth = 3;
    ctx.fillStyle = '#ff8878';

    var x = 0;
    var y = 0;
    var row_w = WIDTH / (cfg.data.length + 1);
    for (i in cfg.data) {
      var item = cfg.data[i];
      x = row_w * i + row_w;
      y = HEIGHT - (item[1] * HEIGHT * per);

      ctx.moveTo(x, y);
      ctx.arc(x, y, 5, 0, 2 * Math.PI, false);
    }
    ctx.fill();

    // 连线
    ctx.beginPath();
    ctx.strokeStyle = '#ff8879'
    ctx.moveTo(row_w, HEIGHT - (cfg.data[0][1] * HEIGHT * per));
    for (i in cfg.data) {
      var item = cfg.data[i];
      x = row_w * i + row_w;
      y = HEIGHT - (item[1] * HEIGHT * per);
      ctx.lineTo(x, y);
    }
    ctx.stroke();

    ctx.lineWidth = 0;
    ctx.lineTo(x, HEIGHT);
    ctx.lineTo(row_w, HEIGHT);
    ctx.fillStyle = 'rgba(255,136,120,0.2)';
    ctx.fill();

    // 写字
    for (i in cfg.data) {
      var item = cfg.data[i];
      x = row_w * i + row_w;
      y = HEIGHT - (item[1] * HEIGHT * per);
      ctx.fillStyle = item[2] || '#595959';
      ctx.font = "14px Arial";
      ctx.fillText(((item[1] * 100)*per >> 0) + '%', x - 10, y - 10);
    }
  };


  // 折线生长动画
  compontent.on('onLoad', function () {
    var s = 0;
    for( i=0; i<100;i++){
      setTimeout(function () {
        s+=.01;
        draw(s);
      },i*10);
    }
  });
  compontent.on('onLeave', function () {
    var s = 1;
    for( i=0; i<100;i++){
      setTimeout(function () {
        s-=.01;
        draw(s);
      },i*10);
    }
  });


  return compontent;
};